Thread: C program to generate array[5] of random characters composed of A-Z and 0-9

  1. #1
    Registered User
    Join Date
    May 2015
    Posts
    1

    Question C program to generate array[5] of random characters composed of A-Z and 0-9

    Can some one help me this is what i've come up with so far.
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        
        char string[5];
        int i;
    
    
        for (i=0;i<5;i++)
            string[i]=(rand()%26)+65;
    
    
            printf("%s ",string);
    
    
    
    
        getch();
        return 0;
    }

    I would really appreciate it.

  2. #2
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    There is no space for the string terminator.
    Try:
    Code:
    …
        char string[6];
    …
        string[5] = '\0';
        printf("String: '%s'\n",string);
    The headerfile 'conio.h' is not standard, avoid it.
    Also, you should not use getch().
    Other have classes, we are class

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    WoodSTokk gave you very good advice that you should heed.

    Code:
    string[i]=(rand()%26)+65;
    Rather than use the magic number 65 here, a preferred method is to just use the character literal 'A'.

    But this approach doesn't solve the problem well, since letters (A - Z) and numbers (0 - 9) are not sequential in the common character sets. Therefore, while a decent attempt, this probably is not the route to a working solution.

    Perhaps you should spend more time thinking about the problem, preferably with a pen a paper, to help you visualize the logic you need to figure out. First figure out how to solve the problem, and only then start writing code.

    There are some clever tricks you could utilize. For instance, instead of trying to pick random numbers that might yield the letters and numbers you need in the character set you're working with, what if you simply put all possible values into an array and randomly selected from that array?

  4. #4
    Registered User cstryx's Avatar
    Join Date
    Jan 2013
    Location
    Canada
    Posts
    123
    You could do something like this:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define MAX_ARR 5
    
    int main(void)
    {
      char arr[MAX_ARR + 1];
      int i, n, rnd;
      srand(time(NULL));
      for (i = 0; i < MAX_ARR; ++i)
      {
        rnd = rand();
        n = (rnd >> 4) & 0xF;
        *(arr + i) = (rnd & 0xF) & 1
                     ? (n % 10) + '0'
                     : (n % 26) + 'A';
      }
      arr[MAX_ARR] = 0;
      puts(arr);
      return 0;
    }
    You could also do 'rnd = rand() % 0xFF;' if you wanted... Technically with the size of the integer generated by rand(), you could use that number to generate multiple characters and digits at a time using the method I posted. Instead of a single 32-bit integer going to waste, you could split that up into 4 8-bit integers to generate data for 4 elements, and you'd only have to fill the last slot after a single call to rand() -- the only problem with this idea is that it depends on the value of the number.. Even though technically if rand() returned 5, it would still be random, but the majority of the values derived from the bits wouldn't appear that way.
    Last edited by cstryx; 07-17-2015 at 09:12 PM.

  5. #5
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I can't understand why cstryx's code is so complicated. Why not just:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define NUM_LETTERS 26
    #define NUM_DIGITS  10
    #define NUM_CHARS   (NUM_LETTERS + NUM_DIGITS)
    #define SIZE        5
    
    int main() {
        srand(time(NULL));
        char a[SIZE+1] = {0};
        for (int i = 0; i < SIZE; ++i) {
            int r = rand() % NUM_CHARS;
            a[i] = r < NUM_LETTERS
                   ? 'A' + r
                   : '0' + r - NUM_LETTERS;
        }
        puts(a);
        return 0;
    }

  6. #6
    Registered User cstryx's Avatar
    Join Date
    Jan 2013
    Location
    Canada
    Posts
    123
    Quote Originally Posted by algorism View Post
    I can't understand why cstryx's code is so complicated. Why not just:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define NUM_LETTERS 26
    #define NUM_DIGITS  10
    #define NUM_CHARS   (NUM_LETTERS + NUM_DIGITS)
    #define SIZE        5
    
    int main() {
        srand(time(NULL));
        char a[SIZE+1] = {0};
        for (int i = 0; i < SIZE; ++i) {
            int r = rand() % NUM_CHARS;
            a[i] = r < NUM_LETTERS
                   ? 'A' + r
                   : '0' + r - NUM_LETTERS;
        }
        puts(a);
        return 0;
    }
    My code at least gives a theoretical 50/50 that the generated char is a digit or an alpha (depending on whether or not you consider rand() to return a theoretical equal amount of odds and evens in terms of probability, given an even # of calls to that function). With yours it's 26:10 odds. If it's not important, then sure you can do this. I was partially trying to get him to think about a few unique alternatives rather than just calling rand() and returning a single char element to an array placeholder. The idea behind my code was that individual bits would represent parts of the condition, and offset from the first value in either set. My code doesn't do it, but with this logic, you could theoretically, equally determine 4 elements at a time with every single call to rand().

    Quote Originally Posted by WoodSTokk View Post
    There is no space for the string terminator.
    Try:
    Code:
    …
        char string[6];
    …
        string[5] = '\0';
        printf("String: '%s'\n",string);
    The headerfile 'conio.h' is not standard, avoid it.
    Also, you should not use getch().
    String's are not required to be null-terminated. If his purpose for this data doesn't require that it should be null-terminated, then his code would be fine. The only problem is that his printf() call requires it to be. If he modified it, it would be fine as:
    Code:
    printf("%.5s\n", string);
    Last edited by cstryx; 07-17-2015 at 10:46 PM.

  7. #7
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by cstryx View Post
    My code at least gives a theoretical 50/50 that the generated char is a digit or an alpha
    Your code "at least" gives something that was neither asked for nor implied in the OP's question. It's a bizarre interpretation.

    And you have a somewhat idealized picture of rand if you think you could use it to generate 4 elements at a time. (Hint: What's the guaranteed (by the standard) value of RAND_MAX? What is it on your system?)

  8. #8
    Registered User cstryx's Avatar
    Join Date
    Jan 2013
    Location
    Canada
    Posts
    123
    Quote Originally Posted by algorism View Post
    Your code "at least" gives something that was neither asked for nor implied in the OP's question. It's a bizarre interpretation.

    And you have a somewhat idealized picture of rand if you think you could use it to generate 4 elements at a time. (Hint: What's the guaranteed (by the standard) value of RAND_MAX? What is it on your system?)
    If he didn't ask that the chance of generating a alpha vs. a digit be the same, then what makes you think that it's correct to assume that he isn't going for it, if the reverse was neither "asked for nor implied" otherwise? That's "bizarre" logic.

    I also never said that unused bits had to be used, I was simply pointing out bit manipulation which allows you to take advantage of letting a single number do multiple things for you, and allowed my code to hint at a strategy. You could let them overlap and use 5 bits instead if you wanted.. There is an issue with my previous code but it was an example aside from the naïve way of doing things. If you'd rather teach originality and avoid creativity--which is undoubtedly beneficial with problem solving, I'll let you do that... There's nothing advantageous about discouraging it though. Aside from that I don't see how you couldn't use the previous value and 4-bits each from rand() itself to generate 4 elements at a time, but I'd be glad to show you that it's possible if you're doubtful. It seems you just thought it was appropriate to make assumptions dictate your judgement before second thought, and I don't respect that.
    Last edited by cstryx; 07-17-2015 at 11:15 PM.

  9. #9
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    In case the question means that at least a Latin letter and a digit is always present in the result (that's how I've interpreted anyway) the logic changes.

    A quick & dirty approach could be something like the following:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <time.h>
    
    #define AB      "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    #define ABLEN   ( sizeof(AB) - 1 )
    #define ARRSIZ  5
    
    int main( void )
    {
        srand( time(NULL) );
    
        char arr[ARRSIZ] = {'\0'};    // not a cstring
        int  nletters = 1 + (rand() % (ARRSIZ-1));
        int  ndigits  = ARRSIZ - nletters;
        printf( "nletters: %d, ndigits: %d\n", nletters, ndigits );
    
        int i = 0;
        while ( ndigits || nletters ) {
            int c = AB[ rand() % ABLEN ];
            if ( nletters && isalpha(c) ) {
                nletters--;
            }
            else if ( ndigits && isdigit(c) ) {
                ndigits--;
            }
            else {
                continue;
            }
            arr[i++] = c;
        }
        printf( "%.5s\n", arr );
    
        return 0;
    }
    PS. I chose to NOT treat arr as a cstring, since the question seems not to imply such a thing. However, if further manipulation of arr can benefit of cstring-like operations, it should be more useful to define/treat it as a cstring from the beginning.
    "Talk is cheap, show me the code" - Linus Torvalds

  10. #10
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Jeez.
    A-Z + 0-9 = 36 possibilities
    Code:
    string[i]=(rand()%36)+'0';        // get 0 to 35, add '0' to convert to number
    if (string[i] > '9') string[i] +=7;  // if above '9', convert to letter
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  11. #11
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by WaltP View Post
    Jeez.
    A-Z + 0-9 = 36 possibilities
    Code:
    string[i]=(rand()%36)+'0';        // get 0 to 35, add '0' to convert to number
    if (string[i] > '9') string[i] +=7;  // if above '9', convert to letter
    That code assumes a specific character set, which the other provided solutions do not.



    While we're on the topic of solutions ... why are there so many posted in this thread? We are here to help people, not spood-feed them answers. The OP was given hints and advice. Before they could even follow up with an attempt of their own, complete solutions were posted.

    Oftentimes, a problem posted by someone new to programming has an easy solution if you know what you're doing. The challenge is trying to frame a response that will guide them towards the solution, so they can find it themselves and learn something in the process.

    You've done the OP no favors. They now have a solution for this assignment, but they've lost some of the practice and experience needed to do further assignments on their own.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program to generate a random sentence
    By ktype in forum C Programming
    Replies: 5
    Last Post: 11-01-2013, 01:01 AM
  2. Replies: 3
    Last Post: 10-16-2013, 11:26 PM
  3. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 07:43 PM
  4. Replies: 11
    Last Post: 07-16-2002, 11:39 AM
  5. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 04:30 AM